package com.awccis.common.websocket;

import com.awccis.common.pool.CustomerPool;
import com.awccis.common.session.CustomerSession;
import com.awccis.common.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

/**
 * @author: njpi
 * @description: 注解中的内容是用户客户端WebSocket的连接url,例如ws://127.0.0.1:80/WebSocket/ws, 结构形式为“ws：//ip:端口/项目名/指定的url”
 */
@ServerEndpoint("/customer")
public class CustomerWsServer {

    private String compareStr = "0";
    private String cmsg = "session";

    /**
     * 日志打印对象
     */
    private static Logger logger = LoggerFactory.getLogger(CustomerWsServer.class);

    /**
     * 连接打开时执行
     *
     * @param session session
     */
    @OnOpen
    public void onOpen(Session session) {
        //超时时间为20秒
        session.setMaxIdleTimeout(20000);
        logger.error("一个乘客客户端连接进来了 -----> 它的sessionId是：" + session.getId());
    }
    
    /**
     * 收到消息时执行
     *
     * @param message message
     * @param session session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        if (compareStr.equals(message)) {
            session.getAsyncRemote().sendText(message);
        }else if (message.startsWith(cmsg)) {
            String customerMsg = message.split("&&")[1];
            CustomerSession customerSession = JsonUtil.str2obj(customerMsg,CustomerSession.class);
            if(!CustomerPool.isContain(customerSession.getPhone())){
                customerSession.setSession(session);
                CustomerPool.addCustomerSession(session.getId(),customerSession);
                logger.error(customerMsg + "乘客上线啦");
            }
        }
    }
    
    /**
     * 连接关闭时执行
     *
     * @param session session
     * @param closeReason closeReason
     */
    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
            if(CustomerPool.isExist(session.getId())){
                logger.error(CustomerPool.getCustomerSession(session.getId()).getName()+"乘客下线啦!");
                CustomerPool.deleteCustomerSession(session.getId());
            }
        logger.error("一个客户端关闭了，c关闭原因是:" + closeReason.getReasonPhrase());
    }
    
    /**
     * 连接错误时执行
     *
     * @param t 异常
     */
    @OnError
    public void onError(Throwable t) {
        t.printStackTrace();
    }

}
